package com.ayi.servlet.backstage; /**
 * @author Ayingzz
 * @create 2021/12/4 14:49
 */

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "imgUploadServlet", value = "/imgUploadServlet")
public class imgUploadServlet extends HttpServlet {

    public static String filename = null;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        factory.setSizeThreshold(1024 * 1024);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        Iterator iter = items.iterator();
        while(iter.hasNext()){
            System.out.println(1);
            FileItem item = (FileItem) iter.next();
            if(!item.isFormField()){

                // 根据时间戳创建头像文件
                filename = System.currentTimeMillis() + ".jpg";
                File f = new File("D://ideaProject/JavaBookShop/image");
                if (!f.exists()) {
                    f.mkdir();
                }
                String imgsrc = f + "/" + filename;

                // 复制文件
                InputStream is = item.getInputStream();
                FileOutputStream fos = new FileOutputStream(imgsrc);
                byte b[] = new byte[1024 * 1024];
                int length = 0;
                while (-1 != (length = is.read(b))) {
                    fos.write(b, 0, length);
                }
                fos.flush();
                fos.close();

            }else {
                System.out.println(item.getFieldName());
                String value = item.getString();
                value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                System.out.println(value);
            }
        }
        request.getSession().setAttribute("img", "http://localhost:8080/image/" + filename);
        request.getSession().setAttribute("allow0", "allow0");
        response.sendRedirect("backStage.jsp");
    }
}
